package com.ruike.alisurface.project_DaTi;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.project_DaTi.adapter.QuestionOptionListAdapter;
import com.ruike.alisurface.project_DaTi.bean.AnswerQuestionBean;
import com.ruike.alisurface.project_DaTi.bean.QuestionBean;
import com.ruike.alisurface.project_DaTi.bean.ResultAnswerBean;
import com.ruike.alisurface.project_DaTi.http.QuestionHttpTools;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: voodoo
 * CreateDate: 2020/07/21 021 05:25 下午
 * Description: 答题界面
 */
public class AnswerQuestionActivity extends BaseAty {

    @BindView(R.id.answerQuestion_content_rlayout)
    RelativeLayout contentRlayout; // 整个答题的内容界面，方便使用此View设置出入动画
    @BindView(R.id.viewQuestionShow_questionContent_tv)
    TextView questionContentTv; // 题目
    @BindView(R.id.viewQuestionShow_questionOptionList_recv)
    RecyclerView questionOptionListRecv; // 选项列表
    @BindView(R.id.viewQuestionShow_submit_rlayout)
    RelativeLayout submitRlayout; // 提交答案按钮
    @BindView(R.id.viewQuestionShow_submit_tv)
    TextView submitTv; // 提交答案按钮上文字
    @BindView(R.id.answerQuestion_time_tv)
    TextView countdownTimeTv; // 倒计时

    List<QuestionBean> questionList;

    int questionTime = 30; // 每道题题目倒计时时间
    int questionAnswerTimer = 0; // 展示正确答案的倒计时时间
    int questionNumber = 4; // 题目总数量
    int currentQuestionNumber = 0; // 当前题目下标
    QuestionOptionListAdapter optionAdapter; // 选项适配器
    MyCountDownTimer questionCountDownTimer; // 题目倒计时显示和控制
    MyCountDownTimer correctAnswerTimer; // 正确答案的倒计时
    MyCountDownTimer errorAnswerTimer; // 错误答案的倒计时

    AnswerQuestionBean answerQuestionBean; // 提交答案上传的对象，包含所有题
    List<AnswerQuestionBean.AnswerListBean> answerListBeans; // 回答的每一题的详情集合
    AnswerQuestionBean.AnswerListBean answerListBean;  // 回答的每一题的详情对象
    List<String> submitAnswers; // 回答的每一题的详情对象中回答的选项列表
    CustomDialog customDialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_answer_question;
    }

    @Override
    protected void initViews() {
        // 界面总倒计时时长 = 题数 * (每一道题计时时长 + 5)  每道题富余5秒钟时长
        startCountdownTimer(questionNumber * (questionTime + 5), null, null);
        submitRlayout.setEnabled(false); // 不可编辑不可点击
        submitRlayout.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {

        showProgressDialog("正在加载题目，请稍后");

        // 设置每道题答题倒计时
        questionCountDownTimer = new MyCountDownTimer(questionTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                L.i(new StringBuffer().append("题目倒计时：").append(millisUntilFinished / 1000 + 1).append("s"));
                countdownTimeTv.setText(String.format(Locale.ENGLISH, "%ds", millisUntilFinished / 1000 + 1));
            }

            @Override
            public void onFinish() {
                submitRlayout.performClick();
            }
        };

        // 回答正确展示倒计时
        correctAnswerTimer = new MyCountDownTimer(500, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                L.i(new StringBuffer().append("回答正确倒计时：").append(millisUntilFinished / 1000 + 1).append("s"));
                countdownTimeTv.setText(String.format(Locale.ENGLISH, "%ds", millisUntilFinished / 1000 + 1));
            }

            @Override
            public void onFinish() {
                nextQuestion(); // 展示下一题的内容
            }
        };

        // 错误答案的倒计时
        errorAnswerTimer = new MyCountDownTimer(questionAnswerTimer * 500, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                L.i(new StringBuffer().append("回答错误倒计时：").append(millisUntilFinished / 1000 + 1).append("s"));
                countdownTimeTv.setText(String.format(Locale.ENGLISH, "%ds", millisUntilFinished / 1000 + 1));
            }

            @Override
            public void onFinish() {
                nextQuestion(); // 展示下一题的内容
            }
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 获取答题策略
        QuestionHttpTools.checkMchJurisdiction(this);
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @OnClick({R.id.viewQuestionShow_submit_rlayout})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.viewQuestionShow_submit_rlayout: // 提交答案按钮

                submitRlayout.setEnabled(false);

                // 取消题目的倒计时
                if (questionCountDownTimer != null) {
                    questionCountDownTimer.cancel();
                }

                // 答题-4 将之前选择的选项转成int元素的List
                List<Integer> answers = new ArrayList<>();
                if (submitAnswers != null && submitAnswers.size() > 0) {
                    for (String answerStr : submitAnswers) {
                        answers.add(Integer.parseInt(answerStr));
                    }
                }
                // 将选中的答案设置到题的详情对象中
                answerListBean.setSubmit_answer(answers);
                // 将设置好的题的对象添加到题目列表中
                answerListBeans.add(answerListBean);

                optionAdapter.setAndwerList(answers); // 设置选中的现象的下标

                // 将选中的选项从小到大排序并且转成：a,b,c,d 的字符串 stringBuffer
                Collections.sort(answers); // 让选中的答案从小到大排序
                StringBuffer stringBuffer = new StringBuffer();
                for (Integer inte : answers) {
                    if (stringBuffer.length() <= 0) {
                        stringBuffer.append(inte);
                    } else {
                        stringBuffer.append(",").append(inte);
                    }
                }

                if (questionCountDownTimer != null) {
                    questionCountDownTimer.cancel();
                }
                // 将转换后的String跟回传的标准答案进行 equals 比较
                if (stringBuffer.toString().equals(questionList.get(currentQuestionNumber).getAnswer_value())) {
                    L.i("选中的答案：正确");
                    submitTv.setText("回答正确");
                    correctAnswerTimer.start(); // 开始倒计时跳转下一题
                } else {
                    L.e("选中的答案：错误");
                    submitTv.setText("回答错误");
                    errorAnswerTimer.start();
                }

                break;
        }
    }

    private void nextQuestion() {
        if (currentQuestionNumber >= questionList.size() - 1) {
            // 答题-5 提交答案之前把前面设置好的List设置到提交的对象中
            answerQuestionBean.setAnswer_list(answerListBeans);

            showProgressDialog("正在提交答案....");
            QuestionHttpTools.submitAnswer(answerQuestionBean, this);
        } else {
            L.i("展示动画进入下一题");

            // 退出动画
            ObjectAnimator outAnimator1 = ObjectAnimator.ofFloat(contentRlayout, "translationX", 0f, -1365f);
            ObjectAnimator outAnimator3 = ObjectAnimator.ofFloat(contentRlayout, "alpha", 1f, 0f);
            AnimatorSet animatorSetOut = new AnimatorSet();
            animatorSetOut.play(outAnimator1).with(outAnimator3);
            animatorSetOut.setDuration(300);
            animatorSetOut.start();

            animatorSetOut.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    setShowQuestion(++currentQuestionNumber);

                    // 进入动画
                    ObjectAnimator outAnimator4 = ObjectAnimator.ofFloat(contentRlayout, "translationX", 1365f, 0f);
                    ObjectAnimator outAnimator6 = ObjectAnimator.ofFloat(contentRlayout, "alpha", 0f, 1f);
                    AnimatorSet animatorSetIn = new AnimatorSet();
                    animatorSetIn.play(outAnimator4).with(outAnimator6);
                    animatorSetIn.setDuration(300);
                    animatorSetIn.start();

                    animatorSetIn.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            questionCountDownTimer.start();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {
                        }
                    });

                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }
    }

    /**
     * 设置显示的问题
     *
     * @param index
     */
    private void setShowQuestion(int index) {

        submitRlayout.setEnabled(true);
        submitRlayout.setVisibility(View.VISIBLE);

        if (questionList != null && questionList.size() > 0 && index >= 0 && index < questionList.size()) {

            QuestionBean questionBean = questionList.get(index);

            // 答题-2 创建一个当前题目的对象 并设置上题目的id和题目编号
            answerListBean = new AnswerQuestionBean.AnswerListBean();
            answerListBean.setQuestion_id(questionBean.getQuestion_id());
            answerListBean.setQuestion_index(questionBean.getQuestion_index());
            submitAnswers = new ArrayList<>(); // 创建一个答案的集合，选项点击的时候直接将下标转为String放进来

//            questionNumberTv.setText(String.format(Locale.ENGLISH, "- 第%d题 -", questionBean.getQuestion_index()));
            questionContentTv.setText(questionBean.getQuestion_content());
            submitTv.setText("提交答案");
            if (optionAdapter == null) {
                optionAdapter = new QuestionOptionListAdapter(this, questionBean.getOptions(), questionBean.getQuestion_type() != 1);
                optionAdapter.setOnItemSelectedListener((i, isSelected, sortStr, isSingles) -> {
                    // 答题-3 添加或者删除点击的选项中sort字段 下一步在按钮点击方法中
                    if (isSelected) {
                        if (isSingles) { // 单选
                            submitAnswers.clear();
                        }
                        submitAnswers.add(sortStr); // 此处添加和删除String格式的不会误以下标删除导致报错
                    } else {
                        submitAnswers.remove(sortStr);
                    }
                    L.e("select index:" + submitAnswers.toString());
                });
                questionOptionListRecv.setLayoutManager(new LinearLayoutManager(this));
                questionOptionListRecv.setAdapter(optionAdapter);
            } else {
                optionAdapter.setList(questionBean.getOptions(), questionBean.getQuestion_type() != 1);
            }
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        try {
            JSONObject jsonObject = new JSONObject(requestJsonStr);
            // 机器自检是否设置答题策略
            if (requestUrl.endsWith("/question/check_mch_jurisdiction")) {
                JSONObject data = jsonObject.optJSONObject("data");
                String strategy_id = data.optString("strategy_id");
                questionNumber = data.optInt("set_question_count");

                if (data.optBoolean("out_of_stock")) {
                    L.i("缺货状态，弹窗询问是否继续答题");
                    if (!AnswerQuestionActivity.this.isFinishing()) {
                        customDialog = new CustomDialog.Builder(AnswerQuestionActivity.this)
                                .setTitle("缺货提醒")
                                .setMessage("当前机器缺货，答完题将无法出货，是否继续答题？")
                                .setPositiveButton("继续答题", (dialogInterface, i) -> {
                                    L.i("继续答题");
                                    // 将策略ID存起来
                                    ShareUtils.getInstance().putString(ShareKey.STRATEGY_ID, strategy_id);
                                    QuestionHttpTools.getQuestion(AnswerQuestionActivity.this); // 获取题目列表
                                })
                                .setNegativeButton("放弃答题", (dialogInterface, i) -> {
                                    L.i("放弃答题");
                                    // 跳转到广告页面
                                    startCountdownTimer(0, null, null);
                                }).create();
                        customDialog.show();
                    }
                } else {
                    L.i("库存可出货状态");
                    // 将策略ID存起来
                    ShareUtils.getInstance().putString(ShareKey.STRATEGY_ID, strategy_id);
                    QuestionHttpTools.getQuestion(AnswerQuestionActivity.this); // 获取题目列表
                }

                return;
            }
            if (requestUrl.endsWith("/question/get_question")) {
                submitRlayout.setEnabled(true); // 可编辑可点击
                JSONArray data = jsonObject.optJSONArray("data");

                // 开始界面整体的倒计时
                startCountdownTimer(questionNumber * (questionTime + 5), null, null);

                questionList = GsonUtils.jsonArray2ModelList(data.toString(), QuestionBean.class);

                // 列表中有存在数据
                if (questionList != null && questionList.size() > 0) {
                    // 答题-1 创建上传答案的对象并设置基础字段的值
                    answerQuestionBean = new AnswerQuestionBean();
                    answerQuestionBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID)); // MchId 机器启动的时候请求到的
                    answerQuestionBean.setStrategy_id(ShareUtils.getInstance().getString(ShareKey.STRATEGY_ID)); // 题目策略id 获取题的时候回传的
                    answerListBeans = new ArrayList<>(); // 题目的集合

                    setShowQuestion(currentQuestionNumber);
                    questionCountDownTimer.start();
                } else {
                    startCountdownTimer(3, null, null);
                    showErrorTip("当前没有要回答的题目");
                }
                return;
            }
            if (requestUrl.endsWith("/question/submit_answer")) {
                ResultAnswerBean resultAnswerBean = GsonUtils.json2Model(jsonObject.optString("data"), ResultAnswerBean.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("resultAnswer", resultAnswerBean);
                startActivity(AnswerRequestActivity.class, bundle);
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        startCountdownTimer(3, null, null);
        showErrorTip(errorMsg);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (customDialog != null) {
            customDialog.dismiss();
            customDialog = null;
        }
        if (questionCountDownTimer != null) {
            questionCountDownTimer.cancel();
            questionCountDownTimer = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
